package com.zjdiepu.www.biz.icbc;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.diepu.www.client.partner.proxy.request.ApplyDiviBackProxyRequest;
import com.diepu.www.client.partner.proxy.request.ApplyDiviStatusProxyRequest;
import com.diepu.www.client.partner.xhh.enums.PartnerErrorCode;
import com.diepu.www.client.proxy.partner.common.DzApplyDiviInfo;
import com.diepu.www.client.proxy.partner.common.YwBusinessBuyerInfo;
import com.diepu.www.client.proxy.partner.common.YwBusinessCarInfo;
import com.diepu.www.client.proxy.partner.common.YwBusinessLoanInfo;
import com.diepu.www.client.proxy.partner.request.divi.ApplyDiviProxyRequest;
import com.diepu.www.client.proxy.partner.request.divi.SynDiviAttachmentsRequest;
import com.zjdiepu.www.base.core.AbstractSysUser;
import com.zjdiepu.www.base.core.BaseException;
import com.zjdiepu.www.base.core.BaseService;
import com.zjdiepu.www.base.enums.status.ApplyDiviStatus;
import com.zjdiepu.www.base.enums.status.BusiStatus;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.status.HzicbcApplyDiviStatus;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.common.consts.SystemConsts;
import com.zjdiepu.www.dao.base.DpBaseDealerInfoMapper;
import com.zjdiepu.www.dao.base.OtherAttachmentsMapper;
import com.zjdiepu.www.dao.dz.DzLoanMiddleBankMapper;
import com.zjdiepu.www.dao.icbc.DzApplyDiviMapper;
import com.zjdiepu.www.dao.yw.YwBusinessBuyerMapper;
import com.zjdiepu.www.dao.yw.YwBusinessCarMapper;
import com.zjdiepu.www.dao.yw.YwBusinessLoanMapper;
import com.zjdiepu.www.dao.yw.YwBusinessMapper;
import com.zjdiepu.www.ibiz.file.IQiniuFileService;
import com.zjdiepu.www.ibiz.icbc.IDzApplyDiviService;
import com.zjdiepu.www.ibiz.zpp.DaiZhongYwService;
import com.zjdiepu.www.model.base.dto.DpBaseDealerInfo;
import com.zjdiepu.www.model.dz.dto.DzLoanMiddleBank;
import com.zjdiepu.www.model.icbc.dto.DzApplyDivi;
import com.zjdiepu.www.model.icbc.ext.DzApplyDiviExt;
import com.zjdiepu.www.model.yw.dto.YwBusiness;
import com.zjdiepu.www.model.yw.dto.YwBusinessBuyer;
import com.zjdiepu.www.model.yw.dto.YwBusinessCar;
import com.zjdiepu.www.model.yw.dto.YwBusinessLoan;
import com.zjdiepu.www.model.zpp.pub.ext.ParamsExt;
import com.zjdiepu.www.proxy.IDiviService;
import com.zjdiepu.www.response.BaseResponse;
import com.zjdiepu.www.response.BooleanResponse;
import com.zjdiepu.www.security.exception.BasePartnerException;

/**
 * dz_申请分期Service层操作实现<br/>
 * @author xiongxiaotun<br/>
 * @time 2017年12月13日 18时05分<br/>
 * @since 1.0<br/>
 */
@Service
public class DzApplyDiviServiceImpl extends BaseService implements IDzApplyDiviService {
	public static final Logger logger = LoggerFactory.getLogger(DzApplyDiviServiceImpl.class);
	@Autowired
	private IDiviService diviService;
	@Autowired
	private DzApplyDiviMapper dzApplyDiviMapper;
	@Autowired
	private YwBusinessMapper ywBusinessMapper;
	@Autowired
	private YwBusinessBuyerMapper ywBusinessBuyerMapper;
	@Autowired
	private YwBusinessLoanMapper ywBusinessLoanMapper;
	@Autowired
	private YwBusinessCarMapper ywBusinessCarMapper;
	@Autowired
	private DpBaseDealerInfoMapper dpBaseDealerInfoMapper;
	@Autowired
	private DzLoanMiddleBankMapper dzLoanMiddleBankMapper;
	@Autowired
	private OtherAttachmentsMapper otherAttachmentsMapper;
	@Autowired
	private DaiZhongYwService daiZhongYwService;
	@Autowired
	private IQiniuFileService qiniuFileService;
	private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
	
	@Override
	@SuppressWarnings("deprecation")
	public BaseResponse<BooleanResponse> saveApplyDiviStatus(ApplyDiviStatusProxyRequest request) {
		String busiId = request.getBusiId();
		YwBusiness ywBusiness = new YwBusiness();
		ywBusiness.setId(busiId);
		
		DzApplyDivi dzApplyDivi = new DzApplyDivi();
		BeanUtils.copyProperties(request, dzApplyDivi);
		dzApplyDivi.setId(request.getDiviId());
		Integer status = request.getStatus();
		dzApplyDivi.initUpdateData(SystemConsts.DEFAULT_ID, "申请分期状态通知");
		try{
			String amount = request.getAmount();
			dzApplyDivi.setAmount(StringUtils.isBlank(amount) ? 0d : Double.valueOf(amount));
			String term = request.getTerm();
			dzApplyDivi.setTerm(StringUtils.isBlank(term) ? 0 : Integer.valueOf(amount));
		} catch (NumberFormatException e) {
			logger.error("parse term {} or amount {} error. params is {}.", request.getTerm(), request.getAmount(), JSON.toJSONString(request));
		}
		try {
			String loandate = request.getLoandate();
			Date loandate_ = StringUtils.isBlank(loandate) ? new Date() : sdf.parse(loandate);
			dzApplyDivi.setLoandate(loandate_);
		} catch (ParseException e) {
			logger.error("parse loandate {} error. params is {}.", JSON.toJSONString(request));
		}
		dzApplyDivi.setBankApplyDiviStatus(String.valueOf(status));
		if(HzicbcApplyDiviStatus.SHOU_LI_SHI_BAI.getCode().equals(status) || HzicbcApplyDiviStatus.SHEN_PI_WEI_TONG_GUO.getCode().equals(status)) {
			dzApplyDivi.setApplyDiviStatus(ApplyDiviStatus.SHEN_QING_SHI_BAI.getCode());
			ywBusiness.setApplyDiviStatus(ApplyDiviStatus.SHEN_QING_SHI_BAI.getCode());
		} else if(HzicbcApplyDiviStatus.FANG_KUAN_CHENG_GONG.getCode().equals(status)){ //放款成功
			dzApplyDivi.setApplyDiviStatus(ApplyDiviStatus.SHEN_QING_CHENG_GONG.getCode());
			ywBusiness.setApplyDiviStatus(ApplyDiviStatus.SHEN_QING_CHENG_GONG.getCode());
			
			//维护放款表和贷中银行登记表
			YwBusiness dbYwBusiness = ywBusinessMapper.selectByPrimaryKey(busiId);
			Integer busiStatus = dbYwBusiness.getBusiStatus();
			if(!BusiStatus.YIN_HANG_YI_FANG_KUAN.getCode().equals(busiStatus)) {
				/*DzLending表*/
				ParamsExt paramsExt = new ParamsExt();
				paramsExt.setTime_lending(dzApplyDivi.getLoandate());
				paramsExt.setBusiId(busiId);
				paramsExt.setCustomerId(dbYwBusiness.getCustomerId());
				//放款金额
				paramsExt.setAmount_lending(dzApplyDivi.getAmount());
				paramsExt.setFeeService(0);
				paramsExt.setAmountLoaning(dzApplyDivi.getAmount());
				daiZhongYwService.diepuBankDaiKuanDataOp(paramsExt, new AbstractSysUser() {
					
					@Override
					public String getName() {
						return SystemConsts.DEFAULT_ID;
					}
					
					@Override
					public String getId() {
						return "银行接口放款";
					}
				});
			}
			
			DzLoanMiddleBank dzLoanMiddleBankParam = new DzLoanMiddleBank();
			dzLoanMiddleBankParam.setBusiId(busiId);
			dzLoanMiddleBankParam.setDpStatus(DpStatus.NORMAL.getCode());
			DzLoanMiddleBank dzLoanMiddleBank = dzLoanMiddleBankMapper.selectRefined(dzLoanMiddleBankParam);
			boolean insert = false;
			if(null == dzLoanMiddleBank) {
				insert = true;
				dzLoanMiddleBank = new DzLoanMiddleBank();
			}
			dzLoanMiddleBank.setCardnoRefund(request.getCardno());
			if(insert) {
				dzLoanMiddleBank.initInsertData(SystemConsts.DEFAULT_ID, "银行接口放款");
				dzLoanMiddleBankMapper.insert(dzLoanMiddleBank);
			} else {
				dzLoanMiddleBank.initUpdateData(SystemConsts.DEFAULT_ID, "银行接口放款");
				dzLoanMiddleBankMapper.updateByPrimaryKeySelective(dzLoanMiddleBank);
			}
		} else {
			ywBusiness.setApplyDiviStatus(status);
			ywBusiness.setRemarks("工商银行返回异常状态记录，请关注applyDiviStatus：" + status);
			logger.error("工商银行返回异常状态记录，请关注applyDiviStatus：{}", status);
		}
		dzApplyDiviMapper.updateByPrimaryKeySelective(dzApplyDivi);
		
		ywBusinessMapper.updateByPrimaryKeySelective(ywBusiness);
		
		return BaseResponse.successWithBoolean(true);
	}
	
	@Override
	public BaseResponse<BooleanResponse> saveApplyDiviBack(ApplyDiviBackProxyRequest request) {
		String busiId = request.getBusiId();
		DzApplyDivi dzApplyDivi = new DzApplyDivi();
		dzApplyDivi.setBusiId(busiId);
		dzApplyDivi.setDpStatus(DpStatus.NORMAL.getCode());
		dzApplyDivi = dzApplyDiviMapper.selectRefined(dzApplyDivi);
		if(null == dzApplyDivi) {
			logger.error("DzApplyDiviServiceImpl.saveApplyDiviBack error. busiId is {},  dzApplyDivi is missing.", busiId);
			return BaseResponse.failWithBoolean(PartnerErrorCode.BUSI_MISSING.getCode(), PartnerErrorCode.BUSI_MISSING.getName());
		}
		
		dzApplyDivi.setReasonBack(request.getBacknote());
		dzApplyDivi.setApplyDiviStatus(ApplyDiviStatus.TUI_HUI.getCode());
		dzApplyDivi.setBankApplyDiviStatus(String.valueOf(HzicbcApplyDiviStatus.SHEN_PI_WEI_TONG_GUO.getCode()));
		dzApplyDivi.initUpdateData(SystemConsts.DEFAULT_ID, "银行申请分期退回");
		dzApplyDiviMapper.updateByPrimaryKeySelective(dzApplyDivi);
		
		YwBusiness ywBusiness = new YwBusiness();
		ywBusiness.setId(busiId);
		ywBusiness.setApplyDiviStatus(ApplyDiviStatus.TUI_HUI.getCode());
		ywBusinessMapper.updateByPrimaryKeySelective(ywBusiness);
		
		return BaseResponse.successWithBoolean(true);
	}
	
	@Override
	public void savePostDiviAttachments(String busiId)	throws BasePartnerException {
		/*
		 * 补充分期资料接口
		 */
		SynDiviAttachmentsRequest request = new SynDiviAttachmentsRequest();
		request.setBusiId(busiId);
		diviService.postDiviAttachments(request);
	}
	
	
	@Override
	public void saveApplyDivi(DzApplyDivi dzApplyDivi)	throws BasePartnerException {
		String id = dzApplyDivi.getId();
		boolean insert = StringUtils.isBlank(id);
		String busiId = dzApplyDivi.getBusiId();
		if(StringUtils.isBlank(busiId)) {
			throw new BaseException("9999", "业务记录ID为空");
		}
		YwBusiness ywBusinessdb = ywBusinessMapper.selectByPrimaryKey(busiId);
		if(null == ywBusinessdb) {
			throw new BaseException("9999", "业务记录丢失");
		}
//		String queryCreditApplyId = ywBusinessdb.getQueryCreditApplyId();
		Boolean commit = dzApplyDivi.getCommit();
		YwBusiness ywBusiness = new YwBusiness();
		ywBusiness.setId(busiId);
		
		DzApplyDivi dzApplyDivi_ = new DzApplyDivi();
		dzApplyDivi_.setBusiId(busiId);
		dzApplyDivi_.setDpStatus(DpStatus.NORMAL.getCode());
		dzApplyDivi_ = dzApplyDiviMapper.selectRefined(dzApplyDivi_);
		
		YwBusinessLoan ywBusinessLoan = new YwBusinessLoan();
		ywBusinessLoan.setBusiId(busiId);
		ywBusinessLoan.setDpStatus(DpStatus.NORMAL.getCode());
		ywBusinessLoan = ywBusinessLoanMapper.selectRefined(ywBusinessLoan);
		//实际贷款
		dzApplyDivi.setAmount(ywBusinessLoan.getLoanAmount());
		//分期数
		dzApplyDivi.setTerm(ywBusinessLoan.getLoanMonth());
		//杭州工行分期状态
		dzApplyDivi.setBankApplyDiviStatus(String.valueOf(HzicbcApplyDiviStatus.DAI_SHOU_LI.getCode()));
		
		Integer applyDiviStatus_ = null;
		if(null != dzApplyDivi_) {
			applyDiviStatus_  = dzApplyDivi_.getApplyDiviStatus();
		}
		
		//检验是否可以修改
		if(null != applyDiviStatus_ && !ApplyDiviStatus.YI_BAO_CUN.getCode().equals(applyDiviStatus_) 
				&& !ApplyDiviStatus.TUI_HUI.getCode().equals(applyDiviStatus_) 
				&& !ApplyDiviStatus.SHEN_QING_SHI_BAI.getCode().equals(applyDiviStatus_)) {
			throw new BaseException(PartnerErrorCode.MODIFIED_LOCKED.getCode(),PartnerErrorCode.MODIFIED_LOCKED.getName());
		}
		
		if(commit != null && commit) {
			YwBusinessCar ywBusinessCar = new YwBusinessCar();
			ywBusinessCar.setBusiId(busiId);
			ywBusinessCar.setDpStatus(DpStatus.NORMAL.getCode());
			ywBusinessCar = ywBusinessCarMapper.selectRefined(ywBusinessCar);
			if(null == ywBusinessCar) {
				throw new BaseException(PartnerErrorCode.RECORD_CAR_MISSING.getCode(), PartnerErrorCode.RECORD_CAR_MISSING.getName());
			}
//			String carType = ywBusinessCar.getCarType();
//			boolean used = "02".equals(carType);
			/**
			 * 检查附件资料是否完整
			 */
			//@see PicIdType
//			OtherAttachmentsExt otherAttachmentsExtParam = new OtherAttachmentsExt();
//			otherAttachmentsExtParam.setBaseWhere();
//			otherAttachmentsExtParam.setDataid(busiId);
//			OtherAttachments otherAttachmentsParam = new OtherAttachments();
//			otherAttachmentsParam.setDpStatus(DpStatus.NORMAL.getCode());
//			otherAttachmentsParam.setDataid(busiId);
//			if(used) {
//				otherAttachmentsParam.setAttachmentSort(AttachmentSort.GUO_HU_QI_CHE_ZI_LIAO.getCode());
//				otherAttachmentsParam.setFileLabel(AttachmentLabel.GUO_HU_DENG_JI_ZHENG_SHU1.getCode());
//			} else {
//				otherAttachmentsParam.setAttachmentSort(AttachmentSort.TI_CHE_QI_CHE_ZI_LIAO.getCode());
//				otherAttachmentsParam.setFileLabel(AttachmentLabel.TI_CHE_QI_CHE_DENGJIZHENG_1.getCode());
//			}
//			OtherAttachments FQ_ZCDJ_1 = otherAttachmentsMapper.selectRefined(otherAttachmentsParam);
//			if(!checkCompleted(FQ_ZCDJ_1)){
//				throw new BaseException(PartnerErrorCode.PIC_DIVI_MISSGING.getCode(), "【分期】注册登记证1缺失");
//			}
//			if(used) {
//				otherAttachmentsParam.setAttachmentSort(AttachmentSort.GUO_HU_QI_CHE_ZI_LIAO.getCode());
//				otherAttachmentsParam.setFileLabel(AttachmentLabel.GUO_HU_DENG_JI_ZHENG_SHU2.getCode());
//			} else {
//				otherAttachmentsParam.setAttachmentSort(AttachmentSort.TI_CHE_QI_CHE_ZI_LIAO.getCode());
//				otherAttachmentsParam.setFileLabel(AttachmentLabel.TI_CHE_QI_CHE_DENGJIZHENG_2.getCode());
//			}
//			OtherAttachments FQ_ZCDJ_2 = otherAttachmentsMapper.selectRefined(otherAttachmentsParam);
//			if(!checkCompleted(FQ_ZCDJ_2)){
//				throw new BaseException(PartnerErrorCode.PIC_DIVI_MISSGING.getCode(), "【分期】注册登记证2缺失");
//			}
//			YwBusinessBuyer ywBusinessBuyer = new YwBusinessBuyer();
//			ywBusinessBuyer.setDpStatus(DpStatus.NORMAL.getCode());
//			ywBusinessBuyer.setCarManType("01");
//			ywBusinessBuyer.setBusiId(busiId);
//			ywBusinessBuyer = ywBusinessBuyerMapper.selectRefined(ywBusinessBuyer);
//			if(null != ywBusinessBuyer) {
//				otherAttachmentsParam.setAttachmentSort(AttachmentSort.ZHONG_YAO_YUAN_JIAN.getCode());
//				otherAttachmentsParam.setFileLabel(AttachmentLabel.JIE_HUN_ZHENG.getCode());
//				OtherAttachments FQ_HYZM_JHZ = otherAttachmentsMapper.selectRefined(otherAttachmentsParam);
//				if(!checkCompleted(FQ_HYZM_JHZ)){
//					throw new BaseException(PartnerErrorCode.PIC_DIVI_MISSGING.getCode(), "【分期】【婚姻证明】结婚证缺失");
//				}
//				otherAttachmentsParam.setAttachmentSort(AttachmentSort.ZHONG_YAO_YUAN_JIAN.getCode());
//				otherAttachmentsParam.setFileLabel(AttachmentLabel.SHOU_RU_ZHENG_MING_PEI_OU.getCode());
//				OtherAttachments FQ_SRZM_2 = otherAttachmentsMapper.selectRefined(otherAttachmentsParam);
//				if(!checkCompleted(FQ_SRZM_2)){
//					throw new BaseException(PartnerErrorCode.PIC_DIVI_MISSGING.getCode(), "【分期】【收入证明】收入证明2缺失");
//				}
//			} else {
//				otherAttachmentsParam.setAttachmentSort(AttachmentSort.ZHONG_YAO_YUAN_JIAN.getCode());
//				otherAttachmentsParam.setFileLabel(AttachmentLabel.DAN_SHEN_JU_JIE_SHU.getCode());
//				OtherAttachments FQ_HYZM_DSZM = otherAttachmentsMapper.selectRefined(otherAttachmentsParam);
//				if(!checkCompleted(FQ_HYZM_DSZM)){
//					throw new BaseException(PartnerErrorCode.PIC_DIVI_MISSGING.getCode(), "【分期】【婚姻证明】单身证明缺失");
//				}
//			}
//			if(used) {
//				otherAttachmentsParam.setAttachmentSort(AttachmentSort.GUO_HU_QI_CHE_ZI_LIAO.getCode());
//				otherAttachmentsParam.setFileLabel(AttachmentLabel.GUO_HU_ER_SHOU_CHE_FA_PIAO.getCode());
//			} else {
//				otherAttachmentsParam.setAttachmentSort(AttachmentSort.TI_CHE_QI_CHE_ZI_LIAO.getCode());
//				otherAttachmentsParam.setFileLabel(AttachmentLabel.TI_CHE_QI_CHE_FA_PIAO.getCode());
//			}
//			OtherAttachments FQ_GCFP = otherAttachmentsMapper.selectRefined(otherAttachmentsParam);
//			if(!checkCompleted(FQ_GCFP)){
//				throw new BaseException(PartnerErrorCode.PIC_DIVI_MISSGING.getCode(), "【分期】购车发票缺失");
//			}
//			otherAttachmentsExtParam.setAttachmentSort(AttachmentSort.JIA_FANG.getCode());
//			otherAttachmentsExtParam.setFileLabel(AttachmentLabel.JIA_FANG_SHANG_MEN_BAI_FANG.getCode());
//			otherAttachmentsExtParam.setRows(3);
//			List<OtherAttachments> FQ_SMZP_1s = otherAttachmentsMapper.selectByExt(otherAttachmentsExtParam);
//			if(CollectionUtils.isEmpty(FQ_SMZP_1s)) {
//				throw new BaseException(PartnerErrorCode.PIC_DIVI_MISSGING.getCode(), "【分期】上门照片缺失");
//			}
//			for(OtherAttachments FQ_SMZP_1 : FQ_SMZP_1s) {
//				if(!checkCompleted(FQ_SMZP_1)){
//					throw new BaseException(PartnerErrorCode.PIC_DIVI_MISSGING.getCode(), "【分期】上门照片缺失");
//				}
//			}
//			otherAttachmentsExtParam.setAttachmentSort(AttachmentSort.ZHU_JIE_REN_QIAN_ZI.getCode());
//			otherAttachmentsExtParam.setFileLabel(AttachmentLabel.ZHU_JIE_REN_QIAN_ZI_ZHAO_PIAN.getCode());
//			otherAttachmentsExtParam.setRows(2);
//			List<OtherAttachments> FQ_KHQZ_1s = otherAttachmentsMapper.selectByExt(otherAttachmentsExtParam);
//			if(CollectionUtils.isEmpty(FQ_KHQZ_1s)) {
//				throw new BaseException(PartnerErrorCode.PIC_DIVI_MISSGING.getCode(), "【分期】客户签字照片缺失");
//			}
//			for(OtherAttachments FQ_KHQZ_1 : FQ_KHQZ_1s) {
//				if(!checkCompleted(FQ_KHQZ_1)){
//					throw new BaseException(PartnerErrorCode.PIC_DIVI_MISSGING.getCode(), "【分期】客户签字照片缺失");
//				}
//			}
//			otherAttachmentsParam.setAttachmentSort(AttachmentSort.ZHONG_YAO_YUAN_JIAN.getCode());
//			otherAttachmentsParam.setFileLabel(AttachmentLabel.HU_KOU_BEN_SHOU_YE.getCode());
//			OtherAttachments FQ_HK_HKB_1 = otherAttachmentsMapper.selectRefined(otherAttachmentsParam);
//			if(!checkCompleted(FQ_HK_HKB_1)){
//				throw new BaseException(PartnerErrorCode.PIC_DIVI_MISSGING.getCode(), "【分期】【户口本】户口本1缺失");
//			}
//			otherAttachmentsParam.setAttachmentSort(AttachmentSort.ZHONG_YAO_YUAN_JIAN.getCode());
//			otherAttachmentsParam.setFileLabel(AttachmentLabel.HU_KOU_BEN_HU_ZHU_YE.getCode());
//			OtherAttachments FQ_HK_HKB_2 = otherAttachmentsMapper.selectRefined(otherAttachmentsParam);
//			if(!checkCompleted(FQ_HK_HKB_2)){
//				throw new BaseException(PartnerErrorCode.PIC_DIVI_MISSGING.getCode(), "【分期】【户口本】户口本2缺失");
//			}
//			otherAttachmentsParam.setAttachmentSort(AttachmentSort.ZHONG_YAO_YUAN_JIAN.getCode());
//			otherAttachmentsParam.setFileLabel(AttachmentLabel.HU_KOU_BEN_BEN_REN_YE.getCode());
//			OtherAttachments FQ_HK_HKB_3 = otherAttachmentsMapper.selectRefined(otherAttachmentsParam);
//			if(!checkCompleted(FQ_HK_HKB_3)){
//				throw new BaseException(PartnerErrorCode.PIC_DIVI_MISSGING.getCode(), "【分期】【户口本】户口本3缺失");
//			}
//			otherAttachmentsParam.setAttachmentSort(AttachmentSort.ZHONG_YAO_YUAN_JIAN.getCode());
//			otherAttachmentsParam.setFileLabel(AttachmentLabel.SHOU_RU_ZHENG_MING_ZHU_JIE_REN.getCode());
//			OtherAttachments FQ_SRZM_1 = otherAttachmentsMapper.selectRefined(otherAttachmentsParam);
//			if(!checkCompleted(FQ_SRZM_1)){
//				throw new BaseException(PartnerErrorCode.PIC_DIVI_MISSGING.getCode(), "【分期】【收入证明】收入证明1缺失");
//			}
//			otherAttachmentsParam.setAttachmentSort(AttachmentSort.YE_WU_FU_JIAN_DA_BAO.getCode());
//			otherAttachmentsParam.setFileLabel(AttachmentLabel.YE_WU_FU_JIAN_DA_BAO.getCode());
//			OtherAttachments FQ_QT_ZIP = otherAttachmentsMapper.selectRefined(otherAttachmentsParam);
//			if(!checkCompleted(FQ_QT_ZIP)){
//				throw new BaseException(PartnerErrorCode.PIC_DIVI_MISSGING.getCode(), "【分期】其他图片(zip包的格式)缺失");
//			}
//			otherAttachmentsParam.setAttachmentSort(AttachmentSort.ZHU_JIE_REN_QIAN_ZI.getCode());
//			otherAttachmentsParam.setFileLabel(AttachmentLabel.ZHU_JIE_REN_QIAN_ZI_SHI_PIN.getCode());
//			OtherAttachments FQ_SPMQSPZL = otherAttachmentsMapper.selectRefined(otherAttachmentsParam);
//			if(!checkCompleted(FQ_SPMQSPZL)){
//				throw new BaseException(PartnerErrorCode.PIC_DIVI_MISSGING.getCode(), "【分期】视频面签视频资料缺失");
//			}
//			
//			/*申请征信*/
//			otherAttachmentsParam.setDataid(queryCreditApplyId);
//			otherAttachmentsParam.setAttachmentSort(AttachmentSort.SHEN_FEN_ZHENG_MING.getCode());
//			otherAttachmentsParam.setFileLabel(AttachmentLabel.SHEN_FEN_ZHENG_MING_ZHENG_MIAN.getCode());
//			OtherAttachments FQ_ZJ_BRZM = otherAttachmentsMapper.selectRefined(otherAttachmentsParam);
//			if(!checkCompleted(FQ_ZJ_BRZM)){
//				throw new BaseException(PartnerErrorCode.PIC_DIVI_MISSGING.getCode(), "【分期】【证件】证件本人正面缺失");
//			}
//			otherAttachmentsParam.setAttachmentSort(AttachmentSort.SHEN_FEN_ZHENG_MING.getCode());
//			otherAttachmentsParam.setFileLabel(AttachmentLabel.SHEN_FEN_ZHENG_MING_FAN_MIAN.getCode());
//			OtherAttachments FQ_ZJ_BRFM = otherAttachmentsMapper.selectRefined(otherAttachmentsParam);
//			if(!checkCompleted(FQ_ZJ_BRFM)){
//				throw new BaseException(PartnerErrorCode.PIC_DIVI_MISSGING.getCode(), "【分期】【证件】证件本人反面缺失");
//			}
//			if(null != ywBusinessBuyer) {
//				otherAttachmentsParam.setAttachmentSort(AttachmentSort.PEI_OU_SHEN_FEN_ZHENG_MING.getCode());
//				otherAttachmentsParam.setFileLabel(AttachmentLabel.PO_SHEN_FEN_ZHENG_MING_ZHENG_MIAN.getCode());
//				OtherAttachments FQ_ZJ_POZM = otherAttachmentsMapper.selectRefined(otherAttachmentsParam);
//				if(!checkCompleted(FQ_ZJ_POZM)){
//					throw new BaseException(PartnerErrorCode.PIC_DIVI_MISSGING.getCode(), "【分期】【证件】证件配偶正面缺失");
//				}
//				otherAttachmentsParam.setAttachmentSort(AttachmentSort.PEI_OU_SHEN_FEN_ZHENG_MING.getCode());
//				otherAttachmentsParam.setFileLabel(AttachmentLabel.PO_SHEN_FEN_ZHENG_MING_FAN_MIAN.getCode());
//				OtherAttachments FQ_ZJ_POFM = otherAttachmentsMapper.selectRefined(otherAttachmentsParam);
//				if(!checkCompleted(FQ_ZJ_POFM)){
//					throw new BaseException(PartnerErrorCode.PIC_DIVI_MISSGING.getCode(), "【分期】【证件】证件配偶反面缺失");
//				}
//			}
//			附件检查完成=============================
			
			if(applyDiviStatus_ == null || ApplyDiviStatus.YI_BAO_CUN.getCode().equals(applyDiviStatus_)) {
				dzApplyDivi.setApplyDiviStatus(ApplyDiviStatus.YI_TI_JIAO.getCode());
				dzApplyDivi.setApplyDiviSubmitTime(new Date());
				ywBusiness.setApplyDiviStatus(ApplyDiviStatus.YI_TI_JIAO.getCode());
			} else {
				dzApplyDivi.setApplyDiviStatus(ApplyDiviStatus.ZAI_CI_TI_JIAO.getCode());
				dzApplyDivi.setApplyDiviSubmitTime(new Date());
				ywBusiness.setApplyDiviStatus(ApplyDiviStatus.ZAI_CI_TI_JIAO.getCode());
			}
			if(ApplyDiviStatus.SHEN_QING_SHI_BAI.getCode().equals(applyDiviStatus_)) {
				dzApplyDiviMapper.deleteByPrimaryKey(dzApplyDivi_.getId()); //删除
				insert = true;
			}
		} else {
			//申请分期标志
			if(!ApplyDiviStatus.TUI_HUI.getCode().equals(applyDiviStatus_)) {
				dzApplyDivi.setApplyDiviStatus(ApplyDiviStatus.YI_BAO_CUN.getCode());
				ywBusiness.setApplyDiviStatus(ApplyDiviStatus.YI_BAO_CUN.getCode());
			} else {
				dzApplyDivi.setApplyDiviStatus(ApplyDiviStatus.TUI_HUI.getCode());
				ywBusiness.setApplyDiviStatus(ApplyDiviStatus.TUI_HUI.getCode());
			}
		}
		YwBusiness ywBusiness_ = ywBusinessMapper.selectByPrimaryKey(busiId);
		if(null != ywBusiness_) {
			String dealerId = ywBusiness_.getDealerId();
			if(StringUtils.isNotBlank(dealerId)) {
				DpBaseDealerInfo dpBaseDealerInfo = dpBaseDealerInfoMapper.selectByPrimaryKey(dealerId);
				if(null != dpBaseDealerInfo) {
					dzApplyDivi.setDealerName(dpBaseDealerInfo.getDealerName());
				}
			}
		}
		if(insert) {
			dzApplyDivi.initInsertData(dzApplyDivi.getModifier(), dzApplyDivi.getModifierName());
			dzApplyDiviMapper.insert(dzApplyDivi);
		 } else {
			dzApplyDivi.initUpdateData(dzApplyDivi.getModifier(), dzApplyDivi.getModifierName());
			// 影响的记录数
			int updateCount = dzApplyDiviMapper.updateByPrimaryKeySelective(dzApplyDivi);
			if(updateCount == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(updateCount > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
		}
		ywBusinessMapper.updateByPrimaryKeySelective(ywBusiness);
		if(commit != null && commit) {
			/*
			 * 申请银行分期接收接口
			 */
			ApplyDiviProxyRequest request = new ApplyDiviProxyRequest();
			request.setBusiId(busiId);
			
			if(null != dzApplyDivi) {
				DzApplyDiviInfo divi = new DzApplyDiviInfo();
				BeanUtils.copyProperties(dzApplyDivi, divi);
				request.setDivi(divi);
			}
			
			YwBusinessBuyer ywBusinessBuyer = new YwBusinessBuyer();
			ywBusinessBuyer.setBusiId(busiId);
			ywBusinessBuyer.setDpStatus(DpStatus.NORMAL.getCode());
			ywBusinessBuyer.setCarManType("03"); //主借人
			ywBusinessBuyer = ywBusinessBuyerMapper.selectRefined(ywBusinessBuyer);
			if(null != ywBusinessBuyer) {
				YwBusinessBuyerInfo buyer = new YwBusinessBuyerInfo();
				BeanUtils.copyProperties(ywBusinessBuyer, buyer);
				request.setBuyer(buyer);
			}
			
			if(null != ywBusinessLoan) {
				YwBusinessLoanInfo loan = new YwBusinessLoanInfo();
				BeanUtils.copyProperties(ywBusinessLoan, loan);
				request.setLoan(loan);
			}
			
			YwBusinessCar ywBusinessCar = new YwBusinessCar();
			ywBusinessCar.setBusiId(busiId);
			ywBusinessCar.setDpStatus(DpStatus.NORMAL.getCode());
			ywBusinessCar = ywBusinessCarMapper.selectRefined(ywBusinessCar);
			if(null != ywBusinessCar) {
				YwBusinessCarInfo car = new YwBusinessCarInfo();
				BeanUtils.copyProperties(ywBusinessCar, car);
				request.setCar(car);
			}
			//申请银行分期接收接口
			diviService.applyDivi(request);
		}
	}
	
	/**
	 * 检查相片是否完整
	 * @param otherAttachments
	 * @return
	 */
//	private boolean checkCompleted(OtherAttachments otherAttachments) {
//		if(null == otherAttachments) { //未同步
//			return false;
//		}
//		String fileName = otherAttachments.getFileName();
//		if(StringUtils.isBlank(fileName)) {
//			return false;
//		}
//		if(!qiniuFileService.exists(fileName)) {
//			return false;
//		}
//		return true;
//	}

	
	@Override
	public void saveUpdateAndDelete(DzApplyDivi dzApplyDivi, OperateType operType) {
		switch (operType) {
		case add:
			dzApplyDivi.initInsertData(dzApplyDivi.getModifier(), dzApplyDivi.getModifierName());
			dzApplyDiviMapper.insert(dzApplyDivi);
			break;
		case edit:
			dzApplyDivi.initUpdateData(dzApplyDivi.getModifier(), dzApplyDivi.getModifierName());
			// 影响的记录数
			int updateCount = dzApplyDiviMapper.updateByPrimaryKeySelective(dzApplyDivi);
			if(updateCount == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(updateCount > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
			break;
		case delete:
			dzApplyDivi.initDeleteData(dzApplyDivi.getModifier(), dzApplyDivi.getModifierName());
			// 影响的记录数
			int deleteCount = dzApplyDiviMapper.updateByPrimaryKeySelective(dzApplyDivi);
			if(deleteCount == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(deleteCount > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
			break;
		default:
			break;
		}
	}
	@Override
	public List<DzApplyDivi> selectByExt(DzApplyDiviExt dzApplyDiviExt) {
		return dzApplyDiviMapper.selectByExt(dzApplyDiviExt);
	}
	
	@Override
	public int countByExt(DzApplyDiviExt dzApplyDiviExt){
		return dzApplyDiviMapper.countByExt(dzApplyDiviExt);
	}
	
	@Override
	public DzApplyDivi selectById(String id) {
		return dzApplyDiviMapper.selectByPrimaryKey(id);
	}
	
	@Override
	public void clearEmpty(Set<String> fieldNames, String id) {
		if(CollectionUtils.isNotEmpty(fieldNames)){
			dzApplyDiviMapper.clearEmpty(fieldNames, id);
		}
	}
	
	@Override
	public int countRefined(DzApplyDivi dzApplyDivi) {
		return dzApplyDiviMapper.countRefined(dzApplyDivi);
	}

	@Override
	public DzApplyDivi selectRefined(DzApplyDivi dzApplyDivi) {
		return dzApplyDiviMapper.selectRefined(dzApplyDivi);
	}
	
	@Override
	public int deletedRefined(DzApplyDivi dzApplyDivi) {
		return dzApplyDiviMapper.deletedRefined(dzApplyDivi);
	}

	@Override
	public boolean repeat(DzApplyDivi dzApplyDivi) {
		int count = countRefined(dzApplyDivi);
		if(count > 1) {
			return true;
		}
		if(count == 0) {
			return false;
		}
		
		if(StringUtils.isBlank(dzApplyDivi.getId())) {
			return true;
		}
		DzApplyDivi dbItem = selectRefined(dzApplyDivi);
		if(null == dbItem) {
			return false;
		}
		return !dzApplyDivi.getId().equals(dbItem.getId());
	}
	
	@Override
	public int updateBatch(String modifier, String modifierName, Integer dpStatus, List<String> ids) {
		Integer current = (int)(System.currentTimeMillis() / 1000);
		return dzApplyDiviMapper.updateBatch(modifier, modifierName, current, dpStatus, ids);
	}
	
	@Override
	public int insertBatch(List<DzApplyDivi> dzApplyDivis) {
		return dzApplyDiviMapper.insertBatch(dzApplyDivis);
	}
}
